import { Handlers, PageProps } from "$fresh/server.ts";
import { Button } from "~/components/Button.tsx";
import { Input } from "~/components/input.tsx";
// import { SelectOption } from "~/components/select.tsx";
// import { Select } from "~/components/select.tsx";
import { addCredential, CredentialMeta } from "~/denokv/resume.ts";
// import { ManipulateType } from "dayjs";
import { getResumeAuthingSDK } from "~/tools/sdk/authing.ts";
/* const units: Array<[ManipulateType, string, boolean?]> = [
  ["milliseconds", "毫秒"],
  ["seconds", "秒", true],
  ["minutes", "分"],
  ["hours", "小时"],
  ["days", "天"],
  ["months", "月"],
  ["years", "年"],
]; */

export const handler: Handlers = {
  async POST(req, ctx) {
    const form = await req.formData();

    const sdk = getResumeAuthingSDK();
    const result = sdk.buildAuthorizeUrl({
      redirectUri: Deno.env.get("location") + "/resume",
      // todo:调整为表单选项
      scope: "profile openid email phone",
      // 应该新增:权限配置列表,以访问额外的自定义资源

      responseMode: "form_post",
      responseType: "code token",
    });
    const params: CredentialMeta = {
      id: result.state!,
      corporateName: form.get("corporateName") as string,
      duration: 0,
      durationUnit: "seconds",
      drives: [],
      createAt: new Date().toISOString(),
    };
    const { ok } = await addCredential(params);
    if (!ok) {
      return ctx.render(params);
    }
    return new Response(null, {
      status: 302,
      headers: {
        location: result.url,
      },
    });
  },
};
export default ({ data, url }: PageProps<Partial<CredentialMeta>>) => {
  return (
    <form
      method="POST"
      action={url.pathname}
      class=" p-6 gap-4 grid xl:grid-cols-1"
    >
      <Input
        defaultValue={data?.corporateName}
        name="corporateName"
        type="text"
        label="公司名称"
        required
        placeholder="公司名称"
      />

      <Button className=" peer-invalid:disabled w-full" formmethod="post">
        生成链接
      </Button>
    </form>
  );
};
